<?php
/**
 * sku属性
 * User: lyl
 * Date: 2019-04-29
 */

namespace Biz\module\Classes\WikiClean;

use Biz\model\GoodsSkuAttr as mGoodsSkuAttr;

class Attribute
{
    private static $filter_value = [];

    /**
     * 执行统一操作
     **/
    public static function run($params, &$data){
        self::_filterData();
        self::_add($params, $data);
    }

    private static function _filterData(){
        self::$filter_value=[];
        //self::$filter_value = mGoodsSkuAttr::select(['id','title'],['status'=>mGoodsSkuAttr::STATUS_PASSED]);
    }

    /**
     * 插入表
     **/
    private static function _add($params, &$data){
        $source_data = json_decode($params['source_data'], true);

        if(!empty($source_data['sku'])){
            if(isset($data['sku']) && !empty($data['sku'])) {
                foreach($data['sku'] as $_k=>&$_v){
                    foreach ($source_data['sku'] as $_ak => &$_av) {
                        if(count($_av['values']) > 1){
                            foreach($_av['values'] as $_vk=>&$_vv){
                                if(isset($_vv['desc'])) {
                                    //$data['attribute'][self::_filter($_av['label'])][$_vk] = $_vv['desc'];
                                    if ( ($_vv['desc'] == $_v['name'] || preg_match('{('.$_vv['desc'].')}', $_v['name'])) && !empty(self::_filter($_av['label']))) {
                                        $data['sku'][$_k]['attribute'][$_ak] = [
                                            'type' => self::_filter($_av['label']),
                                            'image' => isset($_vv['image'])?$_vv['image']:'',
                                        ];
                                    }
                                }
                            }
                        }else{
                            if(!empty(self::_filter($_av['label']))) {
                                $data['sku'][$_k]['attribute'][$_ak] = [
                                    'type' => self::_filter($_av['label']),
                                    'image' => isset($_av['values']['image']) ? $_av['values']['image'] : '',
                                ];
                            }
                        }
                    }
                }
            }
        }
    }

    private static function _filterTree($param, $name = ''){
        $result = '';
        foreach($param as $_k=>&$_v){
            if(!empty($name) && preg_match('{('.$_v['title'].')}', $name)){
                $result = $_v['title'];
                break;
            }
        }
        return $result;
    }


    private static function _filter($param){
        $data = self::_filterTree(self::$filter_value, $param);
        return $data;
    }

}